package com.gengzp.system.service.impl;

import com.gengzp.common.constants.DatePatternConstants;
import com.gengzp.common.enums.GenderEnum;
import com.gengzp.common.exception.BusinessException;
import com.gengzp.common.model.pagination.resp.PaginationResult;
import com.gengzp.common.model.user.entity.SysUser;
import com.gengzp.common.model.user.req.EditSysUserReq;
import com.gengzp.common.model.user.req.PageSysUserReq;
import com.gengzp.common.model.user.resp.PageSysUserResp;
import com.gengzp.common.model.user.resp.SearchSysUserResp;
import com.gengzp.common.utils.DateUtils;
import com.gengzp.permission.utils.PermissionUtils;
import com.gengzp.system.facade.IPermissionFacade;
import com.gengzp.system.facade.ISysUserFacade;
import com.gengzp.system.mapper.SysUserMapper;
import com.gengzp.system.service.ISysUserService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @ClassName UserServiceImpl
 * @Description 用户模块服务层
 * @Author gengzp
 * @Date 2025/5/11 3:31
 */
@Service
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ISysUserFacade sysUserFacade;

    @Autowired
    private IPermissionFacade permissionFacade;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editSysUser(EditSysUserReq req) {
        // 查询当前系统用户信息
        SysUser sysUser = sysUserMapper.selectSysUserById(Long.valueOf(req.getUserId()));
        if (Objects.isNull(sysUser)) {
            throw BusinessException.get("用户不存在");
        }

        // 在数据库中修改用户信息
        sysUser.setUserNickname(req.getUserNickname());
        sysUser.setUserGender(req.getUserGender());
        sysUser.setUserBirthDate(req.getUserBirthDate());
        sysUser.setUserAddress(req.getUserAddress());
        sysUser.setUserIntroduction(req.getUserIntroduction());
        sysUserMapper.updateSysUserById(sysUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeSysUserById(Long userId) {
        // 从数据库中删除用户
        sysUserMapper.deleteSysUserById(userId);
        // 删除用户关联的所有角色
        permissionFacade.removeUserRoleRelationByUserId(userId);
    }

    @Override
    public PaginationResult<PageSysUserResp> pageQuerySysUser(PageSysUserReq req) {
        List<PageSysUserResp> result = Lists.newArrayList();

        // 分页查询系统用户
        List<SysUser> sysUsers = sysUserMapper.pageQuerySysUser(req);
        if (CollectionUtils.isEmpty(sysUsers)) {
            return PaginationResult.get(result, req);
        }

        // 组装返回数据类型
        for (SysUser sysUser : sysUsers) {
            PageSysUserResp pageSysUserResp = new PageSysUserResp();
            pageSysUserResp.setId(String.valueOf(sysUser.getId()));
            pageSysUserResp.setUserAccount(sysUser.getUserAccount());
            pageSysUserResp.setUserNickname(sysUser.getUserNickname());
            pageSysUserResp.setUserGender(sysUser.getUserGender());
            Optional.ofNullable(sysUser.getUserGender()).ifPresent(v -> pageSysUserResp.setUserGenderValue(GenderEnum.getValueByCode(v)));
            pageSysUserResp.setUserBirthDate(sysUser.getUserBirthDate());
            pageSysUserResp.setUserAddress(sysUser.getUserAddress());
            pageSysUserResp.setUserIntroduction(sysUser.getUserIntroduction());
            pageSysUserResp.setCreatedBy(String.valueOf(sysUser.getCreatedBy()));
            pageSysUserResp.setCreatedTime(sysUser.getCreatedTime());
            pageSysUserResp.setLastModifiedBy(String.valueOf(sysUser.getLastModifiedBy()));
            pageSysUserResp.setLastModifiedTime(sysUser.getLastModifiedTime());
            result.add(pageSysUserResp);
        }
        // 填充操作人信息
        sysUserFacade.fillInEntitiesOperatorInfo(result);

        return PaginationResult.get(result, req);
    }

    @Override
    public SearchSysUserResp searchSysUserById(Long userId) {
        // 转换数据类型
        SearchSysUserResp resp = new SearchSysUserResp();

        // 超级管理员, 直接从配置中进行赋值
        if (Objects.equals(PermissionUtils.getSuperAdminUserId(), String.valueOf(userId))) {
            Date superAdminCreatedTime = DateUtils.Str2Date("2001-01-01 00:00:00", DatePatternConstants.YMD_HMS_PATTERN);
            resp.setId(String.valueOf(PermissionUtils.getSuperAdminUserId()));
            resp.setUserAccount(PermissionUtils.getSuperAdminUserAccount());
            resp.setUserNickname("超级管理员");
            resp.setUserGender(GenderEnum.MAN.getCode());
            resp.setUserGenderValue(GenderEnum.MAN.getValue());
            resp.setUserBirthDate(DateUtils.Str2Date("2001-01-01", DatePatternConstants.YMD_PATTERN));
            resp.setUserAddress("浙江杭州临平区");
            resp.setUserIntroduction("当前用户为超级管理员账号，拥有系统所有的角色和权限，且不支持在系统中编辑超级管理员的信息，若有修改超级管理员资料的需求，请前往后端配置文件中更改配置。");
            resp.setCreatedBy(String.valueOf(PermissionUtils.getSuperAdminUserId()));
            resp.setCreatedTime(superAdminCreatedTime);
            resp.setCreatedByUserNickname("超级管理员");
            resp.setLastModifiedBy(String.valueOf(PermissionUtils.getSuperAdminUserId()));
            resp.setLastModifiedTime(superAdminCreatedTime);
            resp.setLastModifiedByUserNickname("超级管理员");
        } else {
            // 非管理员账号, 则从数据库中查出用户信息
            SysUser sysUser = sysUserMapper.selectSysUserById(userId);
            if (Objects.isNull(sysUser)) {
                throw BusinessException.get("当前用户已不存在");
            }

            resp.setId(String.valueOf(sysUser.getId()));
            resp.setUserAccount(sysUser.getUserAccount());
            resp.setUserNickname(sysUser.getUserNickname());
            resp.setUserGender(sysUser.getUserGender());
            resp.setUserGenderValue(Optional.ofNullable(sysUser.getUserGender()).map(GenderEnum::getValueByCode).orElse(null));
            resp.setUserBirthDate(sysUser.getUserBirthDate());
            resp.setUserAddress(sysUser.getUserAddress());
            resp.setUserIntroduction(sysUser.getUserIntroduction());
            resp.setCreatedBy(String.valueOf(sysUser.getCreatedBy()));
            resp.setCreatedTime(sysUser.getCreatedTime());
            resp.setLastModifiedBy(String.valueOf(sysUser.getLastModifiedBy()));
            resp.setLastModifiedTime(sysUser.getLastModifiedTime());
            // 填充操作人信息
            sysUserFacade.fillInEntityOperatorInfo(resp);
        }

        return resp;
    }

}
